package org.example;

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.decodeString("3[a]2[bc]"));
    }
}
class Solution {
    public String decodeString(String s) {
        //初始化数字栈
        Stack<Integer> stackNum = new Stack<>();
        Stack<StringBuilder> stackStr = new Stack<>();
        stackStr.push(new StringBuilder()); //初始化字符串栈
        char[] str = s.toCharArray();

        for (int i = 0; i < s.length(); i++) {
            //判断当前字符是数字
            if(str[i] - '0' >= 0 && str[i] - '0' <= 9){
                int num = 0;
                //提取数字放入到数字栈
                while(i < s.length() && str[i] - '0' >= 0 && str[i] - '0' <= 9){
                    num = num * 10 + (str[i++] - '0');
                }
                i--;
                stackNum.push(num);
            }
            //走到'[', 判断后面的字符是字母
            else if(str[i] == '['){
                i++;
                StringBuilder sb = new StringBuilder();
                while(i < s.length() && str[i] >= 'a' && str[i] <= 'z'){
                    sb.append(str[i++]);
                }
                stackStr.push(sb);
                i--;
            }else if(str[i] == ']'){
                //弹出字符串栈栈顶元素与数字串栈顶元素
                int popNum = stackNum.pop();
                StringBuilder tmp = stackStr.pop();
                for(int j = 0; j < popNum; j++){
                    stackStr.peek().append(tmp);
                }
            }else{
                //当前字符是字母
                StringBuilder sb = new StringBuilder();
                sb.append(str[i]);
                i++;
                while(i < s.length() && str[i] >= 'a' && str[i] <= 'z'){
                    sb.append(str[i++]);
                }
                i--;
                stackStr.peek().append(sb);
            }
        }
        return stackStr.pop().toString();
    }
}